<template>
  <div class="questions-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">
            <span class="title-icon">🧠</span>
            算法题库
            <span class="subtitle">挑战你的编程思维</span>
          </h1>
        </div>
        <div class="stats-section">
          <div class="stat-item">
            <span class="stat-icon">📊</span>
            <div class="stat-content">
              <div class="stat-number">{{ total }}</div>
              <div class="stat-label">题目总数</div>
            </div>
          </div>
          <div class="stat-item">
            <span class="stat-icon">🎯</span>
            <div class="stat-content">
              <div class="stat-number">{{ dataList.length }}</div>
              <div class="stat-label">当前显示</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-card">
        <div class="search-header">
          <span class="search-icon">🔍</span>
          <span class="search-title">智能搜索</span>
        </div>
        <a-form layout="inline" :model="searchParams" @finish="doSearch" class="search-form">
          <div class="form-row">
            <a-form-item class="form-item">
              <div class="input-wrapper">
                <span class="input-icon">📝</span>
                <a-input
                  v-model:value="searchParams.title"
                  placeholder="搜索题目名称..."
                  allow-clear
                  size="large"
                  class="custom-input"
                />
              </div>
            </a-form-item>
            <a-form-item class="form-item">
              <div class="input-wrapper">
                <span class="input-icon">#️⃣</span>
                <a-input
                  v-model:value="searchParams.id"
                  placeholder="输入题目ID..."
                  allow-clear
                  size="large"
                  class="custom-input"
                />
              </div>
            </a-form-item>
            <a-form-item class="form-item">
              <a-button
                type="primary"
                html-type="submit"
                size="large"
                class="search-btn"
                :loading="loading"
              >
                <span class="btn-content">
                  <span class="btn-icon">🚀</span>
                  开始搜索
                </span>
              </a-button>
            </a-form-item>
          </div>
        </a-form>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="table-section">
      <div class="table-card">
        <a-table
          :columns="columns"
          :data-source="dataList"
          :pagination="pagination"
          @change="doTableChange"
          :loading="loading"
          class="custom-table"
          :scroll="{ x: 800 }"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.slotName === 'index'">
              <div class="index-cell">
                <span class="index-number">{{ (searchParams.current - 1) * searchParams.pageSize + index + 1 }}</span>
              </div>
            </template>
            <template v-if="column.slotName === 'title'">
              <div class="title-cell">
                <span class="title-text">{{ record.title }}</span>
                <span class="difficulty-badge" :class="getDifficultyClass(record.difficulty)">
                  {{ getDifficultyText(record.difficulty) }}
                </span>
              </div>
            </template>
            <template v-if="column.slotName === 'tags'">
              <div class="tags-cell">
                <a-tag
                  v-for="tag in JSON.parse(record.tags || '[]')"
                  :key="tag"
                  :color="getTagColor(tag)"
                  class="custom-tag"
                >
                  {{ tag }}
                </a-tag>
                <span v-if="!record.tags || JSON.parse(record.tags || '[]').length === 0" class="no-tags">
                  🏷️ 暂无标签
                </span>
              </div>
            </template>
            <template v-if="column.slotName === 'acceptedRate'">
              <div class="rate-cell">
                <div class="rate-progress">
                  <a-progress
                    :percent="getAcceptedRate(record)"
                    :stroke-color="getRateColor(getAcceptedRate(record))"
                    :show-info="false"
                    size="small"
                  />
                </div>
                <div class="rate-text">
                  {{ `${getAcceptedRate(record)}% (${record.acceptedNum || 0}/${record.submitNum || 0})` }}
                </div>
              </div>
            </template>
            <template v-if="column.slotName === 'createTime'">
              <div class="time-cell">
                <span class="time-icon">📅</span>
                <span class="time-text">{{ dayjs(record.createTime).format('MM-DD HH:mm') }}</span>
              </div>
            </template>
            <template v-if="column.slotName === 'optional'">
              <div class="action-cell">
                <a-button
                  type="primary"
                  @click="toQuestionPage(record)"
                  class="action-btn"
                  size="large"
                >
                  <span class="btn-content">
                    <span class="btn-icon">💻</span>
                    开始挑战
                  </span>
                </a-button>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from "vue-router"
import {
  listQuestionByPageUsingPost,
  listQuestionVoByPageUsingPost
} from '@/api/questionController.ts'
import { message } from 'ant-design-vue'
import Question = API.Question
import dayjs from 'dayjs'
import QuestionVO = API.QuestionVO

const dataList = ref([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.QuestionQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
})

const loadData = async () => {
  loading.value = true
  try {
    const res = await listQuestionByPageUsingPost ({ ...searchParams })
    if (res.data.data) {
      dataList.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
    } else {
      message.error("加载失败，" + res.data.message)
    }
  } catch (error) {
    message.error("网络请求失败")
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})

const columns = [
  {
    title: "序号",
    slotName: "index",
    width: 80,
    align: 'center'
  },
  {
    title: "题目信息",
    slotName: "title",
    width: 300,
  },
  {
    title: "标签分类",
    slotName: "tags",
    width: 200,
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
    width: 150,
    align: 'center'
  },
  {
    title: "创建时间",
    slotName: "createTime",
    width: 120,
    align: 'center'
  },
  {
    title: "操作",
    slotName: "optional",
    width: 120,
    align: 'center',
    fixed: 'right'
  },
]

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 题`,
    pageSizeOptions: ['10', '20', '50'],
  }
})

const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  loadData()
}

const doSearch = () => {
  searchParams.current = 1
  loadData()
}

const router = useRouter()

const toQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  })
}

// 工具函数
const getAcceptedRate = (record: any) => {
  if (!record.submitNum || record.submitNum === 0) return 0
  return Math.round((record.acceptedNum / record.submitNum) * 100)
}

const getRateColor = (rate: number) => {
  if (rate >= 80) return '#52c41a'
  if (rate >= 60) return '#faad14'
  if (rate >= 40) return '#fa8c16'
  return '#f5222d'
}

const getDifficultyClass = (difficulty: string) => {
  const diffMap = {
    '简单': 'easy',
    '中等': 'medium',
    '困难': 'hard'
  }
  return diffMap[difficulty] || 'medium'
}

const getDifficultyText = (difficulty: string) => {
  const diffMap = {
    '简单': '🟢 简单',
    '中等': '🟡 中等',
    '困难': '🔴 困难'
  }
  return diffMap[difficulty] || '🟡 中等'
}

const getTagColor = (tag: string) => {
  const colors = ['blue', 'green', 'orange', 'red', 'purple', 'cyan', 'magenta']
  const hash = tag.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[hash % colors.length]
}
</script>

<style scoped>
.questions-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
}

/* 页面头部 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 2rem 0;
  margin-bottom: 2rem;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 2rem;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0;
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.title-icon {
  font-size: 2.5rem;
  animation: pulse 2s infinite;
}

.subtitle {
  font-size: 1rem;
  color: #666;
  font-weight: 400;
  margin-left: 1rem;
}

.stats-section {
  display: flex;
  gap: 2rem;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 1rem 1.5rem;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 1.5rem;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 700;
  color: #1890ff;
}

.stat-label {
  font-size: 0.875rem;
  color: #666;
}

/* 搜索区域 */
.search-section {
  max-width: 1200px;
  margin: 0 auto 2rem;
  padding: 0 2rem;
}

.search-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 2rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.search-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}

.search-icon {
  font-size: 1.25rem;
}

.search-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #333;
}

.search-form {
  width: 100%;
}

.form-row {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  align-items: end;
  width: 100%;
}

.form-item {
  flex: 1;
  min-width: 200px;
  margin-bottom: 0 !important;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 12px;
  z-index: 1;
  font-size: 1rem;
}

.custom-input {
  padding-left: 2.5rem !important;
  border-radius: 8px;
  border: 2px solid #f0f0f0;
  transition: all 0.3s ease;
}

.custom-input:hover {
  border-color: #40a9ff;
}

.custom-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-btn {
  border-radius: 8px;
  background: linear-gradient(135deg, #1890ff, #096dd9);
  border: none;
  height: 40px;
  padding: 0 2rem;
  font-weight: 600;
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.btn-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.btn-icon {
  font-size: 1rem;
}

/* 表格区域 */
.table-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem 2rem;
}

.table-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 2rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.custom-table {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.ant-table-thead > tr > th) {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border: none;
  font-weight: 600;
  color: #333;
  padding: 1rem;
}

:deep(.ant-table-tbody > tr > td) {
  border: none;
  padding: 1rem;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(24, 144, 255, 0.05);
}

/* 表格单元格样式 */
.index-cell {
  display: flex;
  justify-content: center;
}

.index-number {
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 0.875rem;
}

.title-cell {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.title-text {
  font-weight: 600;
  color: #333;
  font-size: 1rem;
}

.difficulty-badge {
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-weight: 500;
  width: fit-content;
}

.difficulty-badge.easy {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.difficulty-badge.medium {
  background: rgba(250, 173, 20, 0.1);
  color: #faad14;
}

.difficulty-badge.hard {
  background: rgba(245, 34, 45, 0.1);
  color: #f5222d;
}

.tags-cell {
  display: flex;
  flex-wrap: wrap;
  gap: 0.25rem;
}

.custom-tag {
  border-radius: 12px;
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border: none;
}

.no-tags {
  color: #999;
  font-size: 0.875rem;
}

.rate-cell {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  align-items: center;
}

.rate-progress {
  width: 100%;
  max-width: 80px;
}

.rate-text {
  font-size: 0.75rem;
  color: #666;
  text-align: center;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  justify-content: center;
}

.time-icon {
  font-size: 0.875rem;
}

.time-text {
  font-size: 0.875rem;
  color: #666;
}

.action-cell {
  display: flex;
  justify-content: center;
}

.action-btn {
  border-radius: 8px;
  background: linear-gradient(135deg, #52c41a, #389e0d);
  border: none;
  font-weight: 600;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

/* 动画效果 */
@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }

  .page-title {
    font-size: 2rem;
    justify-content: center;
  }

  .stats-section {
    justify-content: center;
  }

  .form-row {
    flex-direction: column;
  }

  .form-item {
    min-width: 100%;
  }

  .search-card,
  .table-card {
    padding: 1rem;
    margin: 0 1rem;
  }

  .questions-container {
    padding: 0;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }

  .title-icon {
    font-size: 1.5rem;
  }

  .subtitle {
    font-size: 0.875rem;
    margin-left: 0.5rem;
  }

  .stat-item {
    padding: 0.75rem 1rem;
  }
}
</style>
